package day9;
//synchronized实现多线程购买商品
//两个线程购买商品  商品库存为100个 必须轮流购买
public
class Demo2 {
    static int goods=100;
    static boolean p;
    static boolean h;
    public synchronized void buy(){
        String name=Thread.currentThread().getName();
        if (goods>0) {
            goods--;
            System.out.println(name+"购买了商品，剩余："+goods+"个");
            try {
                this.notify();
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public static
    void main(String[] args) {
        Demo2 d=new Demo2();
     new Thread(()->{
         for (int i=0;i<100;i++){
             d.buy();
         }
     },"彭正").start();
        new Thread(()->{
            for (int i=0;i<100;i++){
                String name=Thread.currentThread().getName();
                synchronized (d) {
                    if (goods>0) {
                        goods--;
                        System.out.println(name+"购买了商品，剩余："+goods+"个");
                        try {
                            d.notify();
                            d.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        },"胡亚俊").start();
    }
}
